package cn.com.reflect;

import cn.com.domain.Person;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class ReflectDemo2 {
    public static void main(String[] args)  throws Exception {
        Class personClass = Person.class;
        System.out.println("使用public构造器创建对象");
        System.out.println("--------------------------------------");
        Constructor constructor = personClass.getConstructor(String.class, int.class);
        System.out.println(constructor);
        Object person= constructor.newInstance("张三", 23);
        System.out.println(person);

        System.out.println("------------------------------------------");
        Constructor constructor1 = personClass.getConstructor();
        Object person1 = constructor1.newInstance();
        System.out.println(person1);

        System.out.println("-----------------------------------------");
        System.out.println("使用构造器获取构造方法--public");
        System.out.println("-----------------------------------------");
        Constructor[] constructors = personClass.getConstructors();
        for (Constructor constructor2:constructors
             ) {
            System.out.println(constructor2);
        }
        System.out.println("-----------------------------------------");


        System.out.println("获取所有的构造方法--无论是啥类型都获取");
        System.out.println("-----------------------------------------");
        Constructor[] declaredConstructors = personClass.getDeclaredConstructors();
        for (Constructor con:declaredConstructors
             ) {
            System.out.println(con);
        }
        System.out.println("-----------------------------------------");

        System.out.println("使用构造器创建对象，不管是public还是非public");
        System.out.println("---------------------------------");
        Constructor declaredConstructor = personClass.getDeclaredConstructor(String.class, int.class, String.class, String.class, String.class, String.class);
        declaredConstructor.setAccessible(true);
        Object person2 = declaredConstructor.newInstance("王杠精",20,"大傻逼","特能杠","2货一个","天狗");
        System.out.println(person2);
        Field a=personClass.getField("a");
        Object value=a.get(person2);
        System.out.println(value);
        a.set(person2,"狗比");
        System.out.println(person2);
        Class<?> aClass = person2.getClass();
        System.out.println(aClass);
    }
}

